package animation.sort;

import java.awt.*;

import animation.core.AnimationController;

/**
 * Created by IntelliJ IDEA.
 * User: emilio
 * Date: Aug 19, 2004
 * Time: 12:02:15 PM
 * To change this template use File | Settings | File Templates.
 */
public abstract class MergeSortAnimation
        extends SortAnimation
{
    protected int[] aux;
    private int copyFrom, copyTo;
    private float copyStep;
    private int[] arrayFrom;

    protected void unmarkAll()
    {
        copyFrom = copyTo = -1;
        super.unmarkAll();
    }

    protected void initAuxArray(int length)
    {
        if (aux == null || aux.length != length) {
            aux = new int[length];
        }
    }

    protected void paintArray(Graphics2D g, int[] array, int slotOffset,
                              int yoffset, int height, int swapFrom,
                              int swapTo, int cmpFrom, int cmpTo)
    {
        super.paintArray(g, array, slotOffset, yoffset, height / 2, -1, -1, -1, -1);
        initAuxArray(array.length);
        super.paintArray(g, aux, slotOffset, yoffset + height / 2, height / 2, -1, -1, cmpFrom, cmpTo);
        drawCopy(g, copyStep, arrayFrom, copyFrom, copyTo, slotOffset, height/2);
    }

    private void drawCopy(Graphics2D g, float step, int[] arrayFrom, int from,
                          int to, int offset, int height)
    {
        if (from != -1 && to != -1) {
            final float dispX = (to - from) * step;
            final float dispY = height * step;
            int x = Math.round(SPACE + offset * (from + dispX));
            int y = Math.round(arrayFrom == aux ? height - dispY : dispY);
            drawSlot(g, TMAIN, LIGHT_TMAIN, arrayFrom, x, from, offset, y, height);
        }
    }


    protected void copy(int[] array1, int i, int[] array2, int j)
            throws Exception
    {

        if (speed == AnimationController.MAX_SPEED) {
            doSleep(1000);
        }
        else {
            arrayFrom = array2;
            copyFrom = j;
            copyTo = i;
            animating = true;
            int time = 1000;
            int steps = (AnimationController.MAX_SPEED - speed) / 5 + 1;
            int timeslot = time / steps;
            for (int step = 1; step <= steps; step++) {
                copyStep = (float) step / steps;
                doSleep(timeslot);
                time -= timeslot;
            }
            if (time > 0) {
                doSleep(time);
            }
            copyFrom = copyTo = -1;
            animating = false;
        }
        array1[i] = array2[j];
    }

}
